$NG.AllReady(function (page, { useAction, useBeforeClick, useValuesChange, useClick, useUpdateRow, subscribe, useUpdateRows }) {
    console.log('detail Ready');
    const mstform = $NG.getCmpApi('p_form_htzlyj_m');
    const dgrid = $NG.getCmpApi('p_form_htzlyj_d1');
    const toolbar = $NG.getCmpApi("toolbar_top")
    // toolbar.insert({
    //     id: "myadd",
    //     text: "debug测试",
    //     iconCls: "icon-New"
    // });
    useClick(() => {
        importAttachment()
    }, 'myadd')
    const config = {
        u_yjwj_bak: [],
        attachment_detali: []
    }
    importAttachment()
    // 定义文件类型映射关系
    const FILE_TYPE_MAP = {
        "01": "全选",
        "02": "招标文件",
        "03": "投标文件",
        "04": "开标记录",
        "05": "授权书",
        "06": "保函扫描件"
    };

    // 存储原始数据备份
    let isFiltering = false; // 标记是否正在执行过滤操作

    // 在网格渲染后备份原始数据
    originalGridData = dgrid.getRows().map(row => ({ ...row }));
    console.log('原始数据已备份', originalGridData);
    // useAction('afterRender')(() => {
    //     // 备份原始数据

    //     // 页面加载时初始化过滤
    //     const initialValues = mstform.getItem('u_yjwj').getValue() || [];
    //     filterGridData(initialValues);
    // }, 'p_form_htzlyj_d1');

    // 监听u_yjwj多选框变化
    useValuesChange(({ args }) => {
        let selectedValues = mstform.getItem('u_yjwj').getValue() || [];
        if (JSON.stringify(selectedValues) == JSON.stringify(config.u_yjwj_bak)) {
            return
        }
        console.log('多选框值变化:', selectedValues);
        if (selectedValues.includes('01')) {
            if (config.u_yjwj_bak.includes('01')) {
                const temp = selectedValues.filter(el => {
                    if (el != '01') {
                        return true
                    } else {
                        return false
                    }
                })
                mstform.getItem('u_yjwj').setValue([...temp])
                config.u_yjwj_bak = [...temp]
            } else {
                mstform.getItem('u_yjwj').setValue(['01', '02', '03', '04', '05', '06'])
                config.u_yjwj_bak = ['01', '02', '03', '04', '05', '06']
            }

        } else {
            // 取消全选
            if (config.u_yjwj_bak.includes('01')) {
                mstform.getItem('u_yjwj').setValue([])
                config.u_yjwj_bak = []
            } else {
                if (selectedValues.join(',') == ['02', '03', '04', '05', '06'].join(',')) {
                    mstform.getItem('u_yjwj').setValue(['01', '02', '03', '04', '05', '06'])
                    selectedValues = ['01', '02', '03', '04', '05', '06']
                }
            }
            config.u_yjwj_bak = [...selectedValues]
        }

        // 改变明细
        let temp = []
        if (config.u_yjwj_bak.includes("01")) {
            temp = [...config.attachment_detali]
        } else {
            config.u_yjwj_bak.forEach(item => {
                const ty = config.attachment_detali.filter(it => {
                    if (it.u_fjlx == FILE_TYPE_MAP[item]) {
                        return true
                    }
                    return false
                })
                temp.push(...ty)
            })
        }
        dgrid.clearRows().then(() => {
            dgrid.addRows(temp)
        })

    }, "p_form_htzlyj_m.u_yjwj");

    useValuesChange(({ args }) => {
        console.log(`args`, args);
        mstform.getItem("u_htbh").setValue(args[0].u_htmc.origin.bill_no)
        importAttachment()
    }, "p_form_htzlyj_m.u_htmc")
    // 确保在数据变化时更新备份
    useUpdateRows(({ args }) => {
    }, 'p_form_htzlyj_d1');

    function importAttachment() {
        const phid = mstform.getItem("u_htmc").getValue()
        if (!phid) return
        dgrid.clearRows()
        config.attachment_detali = []
        mstform.getItem("u_yjwj").setValue([])
        // %@U2FsdGVkX1/48sqlnayO5kmEzOMw😀tubmnRDZyvuvQDO6sSC9+HlPiayaVDUccrlSQ😀ZWZP6kCphBKI😀410ZQQ==&&0.0.5
        $NG.execServer("getTbqkzjAttachmentInfo", { phid }, async (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data)[0].extendObjects
            if (datas) {
                const fid = JSON.parse(datas.user_fjxx)?.u_fid
                if (!fid) return
                // %@U2FsdGVkX1+V++sh83LGMTciC1cxx2xzudd2tfk+0bwsxU1xv5+KCIHCoRXz+TikTP581mlr7lWCdQa5😀Q2DR😀==&&0.0.5
                await $NG.execServer("getTbqkzj2AttachmentInfo", { fid }, async (res2) => {
                    let fids = []
                    if (res2.count == 0) return
                    const attachments = JSON.parse(res2.data)[0].extendObjects
                    fids.push(attachments.u_fj)
                    fids.push(attachments.u_tbwj)
                    fids.push(attachments.u_kbjl)
                    fids.push(attachments.u_sqwts)
                    fids.push(attachments.u_bhsmj)
                    // %@U2FsdGVkX196wZVP6Zu9qoRSo😀jtWFB0CGcgiMIdToGHXG/OU/VP11WmPnYR0nDF1ugbOdvVMN2FjdVg95😀qH😀==&&0.0.5
                    fids = fids.filter(it => {
                        if (!it.split('@@')[1] || it.split('@@')[1] == '0') {
                            return false
                        } else {
                            return true
                        }
                    })
                    // %@U2FsdGVkX1907k8UUKN+psiBVyHjZN66S22DjfO1mgg/YoRiFr/JTGphwMofzkYd&&0.0.5
                    fids = fids.map(el => el.split('@@')[0] || '无')
                    const rows = []
                    for (let i = 0; i < fids.length; i++) {
                        const asrId = fids[i]
                        // %通过asr获取fid，一个个的传入到新的asr上面赋值给明细
                        await $NG.execServer("getAttachnentByAseSession", { asrId }, async (result) => {
                            if (result.count == 0) return
                            const datas = JSON.parse(result.data).reduce((value, it) => {
                                value.push(it.extendObjects)
                                return value
                            }, [])
                            for (let j = 0; j < datas.length; j++) {
                                const item = datas[j]
                                const asrcode = generateUUID()
                                const json = {
                                    "asrSessionGuid": asrcode,
                                    "approved": "0",
                                    "typeId": 0,
                                    "asrFids": [
                                        item.asr_fid
                                    ],
                                    "asrTable": "system",
                                    "asrCode": null,
                                    "busTypeCode": "htzlyj",
                                }
                                // 导入开始 
                                const url = 'http://10.52.119.173:30847/JFileSrv/reactAttach/importFromMyAttach'; // 请求地址

                                try {
                                    const response = await fetch(url, {
                                        method: 'POST',
                                        headers: {
                                            'Content-Type': 'application/json',
                                            'dbtoken': '0001'
                                        },
                                        body: JSON.stringify(json)
                                    });

                                    if (!response.ok) {
                                        throw new Error('网络响应不是OK');
                                    }

                                    const result = await response.json();
                                    const mp = {
                                        0: '招标文件',
                                        1: '投标文件',
                                        2: '开标记录',
                                        3: '授权书',
                                        4: '保函扫描件'
                                    }
                                    rows.push({
                                        u_fjlx: mp[i],
                                        u_fj: asrcode + '@@1',
                                        u_fjmc: item.asr_name,
                                        u_scr: item.asr_fillname,
                                        u_scsj: item.asr_filldt

                                    });
                                    console.log('成功收到响应:', result);
                                } catch (error) {
                                    console.error('请求失败:', error);
                                }
                            }
                            // 查找一个删除一个asr ， 用于后面判断
                            fids[i] = false
                        })
                    }
                    // %@U2FsdGVkX1+Ci53/sQW0+NDdGrBKG2B/Gfc+HHxV5ycSkx😀ejI9Jhv98pUFmLBGw&&0.0.5
                    window._catch_fidTime = setInterval(() => {
                        const temp = fids.filter((ip) => ip)
                        console.log(`temp`, temp);
                        if (temp.length == 0) {
                            clearInterval(window._catch_fidTime)
                            console.log(`添加的数据`, rows);
                            // dgrid.addRows(rows)
                            config.attachment_detali = rows
                        }
                    }, 1000)
                })
            }
        })
    }


    function generateUUID() {
        // UUID v4的格式为：xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
        // 其中y位为8、9、A或B

        // 生成随机16进制数的辅助函数
        function randomHex() {
            // 生成0-0xffff的随机数，转换为16进制并补全4位
            return Math.floor((1 + Math.random()) * 0x10000)
                .toString(16)
                .substring(1);
        }

        // 生成y位的值（8-11之间的随机数，16进制为8-b）
        const y = Math.floor(Math.random() * 4) + 8;

        return (
            randomHex() + '-' +
            randomHex() + '-' +
            '4' + randomHex().substring(1) + '-' +  // 第3段以4开头
            y.toString(16) + randomHex().substring(1) + '-' +  // 第4段以y开头
            randomHex() + randomHex()
        );
    }

}, function () {
    console.log('list Ready');
});